<template>
    <view class="chat-session">
        <view class="header">
            <view class="user-info">
                <image class="avatar" :src="sessionInfo.userAvatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
                <view class="info">
                    <text class="username">{{ sessionInfo.username || '用户' + sessionInfo.userId }}</text>
                    <text class="status" :class="sessionInfo.sessionStatus.toLowerCase()">{{ getStatusText(sessionInfo.sessionStatus) }}</text>
                </view>
            </view>
            <view class="actions">
                <button class="action-btn" @click="showTransferDialog" v-if="sessionInfo.sessionStatus === 'ACTIVE'">转接</button>
                <button class="action-btn" @click="showEndDialog" v-if="sessionInfo.sessionStatus === 'ACTIVE'">结束</button>
            </view>
        </view>

        <scroll-view class="message-list" scroll-y="true" :scroll-top="scrollTop" @scrolltoupper="loadMoreMessages">
            <view v-if="loading" class="loading">加载中...</view>
            <view v-for="message in messages" :key="message.id" class="message-item" :class="message.senderType.toLowerCase()">
                <image class="avatar" :src="message.senderType === 'USER' ? (sessionInfo.userAvatar || '/static/images/default-avatar.png') : '/static/images/service-avatar.png'" mode="aspectFill"></image>
                <view class="message-content">
                    <text class="message-text">{{ message.content }}</text>
                    <text class="message-time">{{ formatTime(message.createTime) }}</text>
                </view>
            </view>
        </scroll-view>

        <view class="input-area">
            <input class="message-input" v-model="inputMessage" placeholder="请输入消息" @confirm="sendMessage" />
            <button class="send-btn" @click="sendMessage">发送</button>
        </view>

        <!-- 转接对话框 -->
        <uni-popup ref="transferPopup" type="dialog">
            <uni-popup-dialog
                title="转接会话"
                :before-close="true"
                @confirm="handleTransfer"
                @close="closeTransferDialog"
            >
                <view class="transfer-form">
                    <input class="input" v-model="transferReason" placeholder="请输入转接原因" />
                </view>
            </uni-popup-dialog>
        </uni-popup>

        <!-- 结束会话对话框 -->
        <uni-popup ref="endPopup" type="dialog">
            <uni-popup-dialog
                title="结束会话"
                :before-close="true"
                @confirm="handleEndSession"
                @close="closeEndDialog"
            >
                <view class="end-form">
                    <input class="input" v-model="endReason" placeholder="请输入结束原因" />
                </view>
            </uni-popup-dialog>
        </uni-popup>
    </view>
</template>

<script>
import { getSessionDetail, getSessionMessages, sendSessionMessage, transferSession, endSession } from '@/api/chat';

export default {
    data() {
        return {
            sessionId: '',
            sessionInfo: {},
            messages: [],
            inputMessage: '',
            loading: false,
            scrollTop: 0,
            page: 1,
            size: 20,
            transferReason: '',
            endReason: '',
            pollingInterval: null
        }
    },
    onLoad(options) {
        if (options.id) {
            this.sessionId = options.id;
            this.loadSessionInfo();
            this.loadMessages();
            this.startPolling();
        }
    },
    onUnload() {
        this.stopPolling();
    },
    methods: {
        async loadSessionInfo() {
            try {
                const response = await getSessionDetail(this.sessionId);
                if (response && response.data) {
                    this.sessionInfo = response.data;
                }
            } catch (error) {
                console.error('加载会话信息失败:', error);
                uni.showToast({
                    title: '加载会话信息失败',
                    icon: 'none'
                });
            }
        },
        async loadMessages() {
            if (this.loading) return;
            this.loading = true;
            try {
                const response = await getSessionMessages(this.sessionId);
                if (response && response.data) {
                    this.messages = response.data;
                }
            } catch (error) {
                console.error('加载消息失败:', error);
                uni.showToast({
                    title: '加载消息失败',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },
        async sendMessage() {
            if (!this.inputMessage.trim()) return;
            try {
                await sendSessionMessage(this.sessionId, this.inputMessage);
                this.inputMessage = '';
                this.loadMessages();
            } catch (error) {
                console.error('发送消息失败:', error);
                uni.showToast({
                    title: '发送消息失败',
                    icon: 'none'
                });
            }
        },
        showTransferDialog() {
            this.$refs.transferPopup.open();
        },
        closeTransferDialog() {
            this.transferReason = '';
            this.$refs.transferPopup.close();
        },
        async handleTransfer() {
            if (!this.transferReason.trim()) {
                uni.showToast({
                    title: '请输入转接原因',
                    icon: 'none'
                });
                return;
            }
            try {
                await transferSession(this.sessionId, null, this.transferReason);
                this.closeTransferDialog();
                uni.showToast({
                    title: '转接成功',
                    icon: 'success'
                });
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
            } catch (error) {
                console.error('转接失败:', error);
                uni.showToast({
                    title: '转接失败',
                    icon: 'none'
                });
            }
        },
        showEndDialog() {
            this.$refs.endPopup.open();
        },
        closeEndDialog() {
            this.endReason = '';
            this.$refs.endPopup.close();
        },
        async handleEndSession() {
            if (!this.endReason.trim()) {
                uni.showToast({
                    title: '请输入结束原因',
                    icon: 'none'
                });
                return;
            }
            try {
                await endSession(this.sessionId, this.endReason);
                this.closeEndDialog();
                uni.showToast({
                    title: '会话已结束',
                    icon: 'success'
                });
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
            } catch (error) {
                console.error('结束会话失败:', error);
                uni.showToast({
                    title: '结束会话失败',
                    icon: 'none'
                });
            }
        },
        formatTime(time) {
            if (!time) return '';
            const date = new Date(time);
            return `${date.getHours()}:${date.getMinutes()}`;
        },
        getStatusText(status) {
            const statusMap = {
                'ACTIVE': '进行中',
                'WAITING': '等待中',
                'ENDED': '已结束',
                'TRANSFERRED': '已转接'
            };
            return statusMap[status] || status;
        },
        startPolling() {
            this.pollingInterval = setInterval(() => {
                this.loadSessionInfo();
                this.loadMessages();
            }, 5000);
        },
        stopPolling() {
            if (this.pollingInterval) {
                clearInterval(this.pollingInterval);
            }
        }
    }
}
</script>

<style>
.chat-session {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f5f5f5;
}

.header {
    background-color: #fff;
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #eee;
}

.user-info {
    display: flex;
    align-items: center;
}

.avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 20rpx;
}

.info {
    display: flex;
    flex-direction: column;
}

.username {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.status {
    font-size: 24rpx;
    padding: 4rpx 12rpx;
    border-radius: 8rpx;
    margin-top: 4rpx;
}

.status.active {
    background-color: #e8f5e9;
    color: #4caf50;
}

.status.waiting {
    background-color: #fff3e0;
    color: #ff9800;
}

.status.ended {
    background-color: #f5f5f5;
    color: #9e9e9e;
}

.status.transferred {
    background-color: #e3f2fd;
    color: #2196f3;
}

.actions {
    display: flex;
    gap: 20rpx;
}

.action-btn {
    font-size: 24rpx;
    padding: 8rpx 20rpx;
    border-radius: 6rpx;
    background-color: #f5f5f5;
    color: #666;
    border: 1rpx solid #ddd;
}

.message-list {
    flex: 1;
    padding: 20rpx;
}

.message-item {
    display: flex;
    margin-bottom: 20rpx;
}

.message-item.user {
    flex-direction: row-reverse;
}

.message-content {
    max-width: 70%;
    margin: 0 20rpx;
}

.message-text {
    padding: 20rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    word-break: break-all;
}

.user .message-text {
    background-color: #007AFF;
    color: #fff;
}

.service .message-text {
    background-color: #fff;
    color: #333;
}

.message-time {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
    display: block;
}

.input-area {
    background-color: #fff;
    padding: 20rpx;
    display: flex;
    align-items: center;
    border-top: 1rpx solid #eee;
}

.message-input {
    flex: 1;
    height: 72rpx;
    background-color: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
    margin-right: 20rpx;
}

.send-btn {
    width: 120rpx;
    height: 72rpx;
    background-color: #007AFF;
    color: #fff;
    border-radius: 36rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.loading {
    text-align: center;
    padding: 20rpx;
    color: #999;
    font-size: 24rpx;
}

.transfer-form,
.end-form {
    padding: 20rpx;
}

.input {
    width: 100%;
    height: 72rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
}
</style> 